Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix flash attention speed issue #32028

Merged
merged 1 commit into from
Jul 23, 2024

Conversation

Cyrilvallez
Copy link
Member

@Cyrilvallez Cyrilvallez commented Jul 17, 2024

What does this PR do?

#31961 inadvertently impacted the performance of the forward with FA2 quite negatively due to the very recurrent call to is_flash_attn_greater_or_equal("2.4.1"). This fixes the issue by adding a lru_cache to the function for fast lookup, allowing to retain the same performance as before the linked PR was merged.

Simple benchmark

I ran the snippet on a RTX 4090 card

from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
import numpy as np

model_name = 'meta-llama/Meta-Llama-3-8B'
dtype = torch.bfloat16
model = AutoModelForCausalLM.from_pretrained(model_name, attn_implementation='flash_attention_2',
                                            torch_dtype=dtype, low_cpu_mem_usage=True).cuda()
tokenizer = AutoTokenizer.from_pretrained(model_name)
# Random token sequence
input = torch.randint(0, 1000, (1, 500), device='cuda')

times = []
for _ in range(10):
    start = torch.cuda.Event(enable_timing=True)
    end = torch.cuda.Event(enable_timing=True)
    start.record()
    # Generate 200 tokens
    out = model.generate(input, max_new_tokens=200, min_new_tokens=200, do_sample=False)
    end.record()
    torch.cuda.synchronize()
    times.append(start.elapsed_time(end) / 1000)  # time in seconds


print(np.mean(times))

This gives:

# Before the fix
>>> 5.863476708984375 s

# After the fix
>>> 4.165076806640625 s

Who can review?

@ArthurZucker @gante

Copy link
Collaborator

@ArthurZucker ArthurZucker left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, we can also just do it once, at the top of the file WDYT?

@HuggingFaceDocBuilderDev

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

@Cyrilvallez
Copy link
Member Author

LGTM, we can also just do it once, at the top of the file WDYT?

@ArthurZucker, usually I would agree if the function is only used in a single location, but in modeling_gemma2.py we also have an open call softcap=self.config.attn_logit_softcapping if is_flash_attn_greater_or_equal("2.6.0") else None in every FA2 forward call. Thus adding the lru_cache makes Gemma2 FA2 significantly faster as well (~2x on the previous snippet for Gemma2 9B). We could call the function a single time at the top of modeling_gemma2.py as well, but it may mean that we add large overhead to FA2 to other models in the future if we are not always careful about is_flash_attn_greater_or_equal(). Plus I am not aware of any downsides of lru_cache for this kind of helper functions (are there any?), so I think it works nicely in this case.

Copy link
Collaborator

@ArthurZucker ArthurZucker left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sounds good yeah, let's go with that

@ArthurZucker ArthurZucker merged commit a5b226c into huggingface:main Jul 23, 2024
21 checks passed
@Cyrilvallez Cyrilvallez deleted the fix-flash-attn branch August 30, 2024 08:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants